<?php
/**
 * 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_App
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: App.php 17 2009-11-15 01:58:48Z nkeyes $
 */

class Bushido_App
{
	protected $frontController = null;

	/**
	 * 
	 * @return Zend_Controller_Front
	 */
	public function getFrontController()
	{
		return $this->frontController;
	}
	
	/**
	 * 
	 * @param string $uid
	 * @return void
	 */
	public static function setUserInfo($uid)
	{	
		$appConfig = Zend_Controller_Front::getInstance()->getParam('appconfig');
		//Zend_Debug::dump($uid, '$uid passed to app::setinfo');
		if($appConfig['requirelogin'])
		{
			//Zend_Debug::dump("login req");
			//Zend_Debug::dump($uid, '$uid passed to ldap');
			$userInfo = self::_setLDAPUserInfo($uid);
			//Zend_Debug::dump($userInfo, '$userInfo after ldap');
			
			$session = Bushido_App::session();
			if(isset($session->userInfo) && isset($session->userInfo['admin_bushido_user_id']))
			{
				$session->userInfo = array_merge($userInfo, array('admin_bushido_user_id' => $session->userInfo['admin_bushido_user_id']));
			}
			else
			{
				$session->userInfo = $userInfo;
			}
			
			//Zend_Debug::dump($session, '$session');
			//Zend_Debug::dump(Bushido_App::session()->userInfo, 'session from app');exit;
			self::setUserRoles($userInfo);
			self::setUserTeams($userInfo);
		}
		else
		{
			//Zend_Debug::dump("no login req");
		}
	}
	
	
	/**
	 * 
	 * @param $uid
	 * @return array
	 */
	public static function getLDAPUserInfo($uid)
	{
		//Zend_Debug::dump("ldap func login req");
		$authConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/auth.xml', APPLICATION_ENV);
		$ldap = new Bushido_Ldap($authConfig->ldap->toArray());
		
		$result = $ldap->search(Zend_Ldap_Filter::equals('uid', $uid), $authConfig->baseDn, null, array('cn', 'employeenumber', 'nsRole'));
		$userInfo = $result->toArray();
		
		$userInfo = $userInfo[0];

		foreach($userInfo as $key => &$value)
		{
			if(is_numeric($key) || $key == 'count')
			{
				unset($userInfo[$key]);
			}
			elseif(is_array($value))
			{
				if(isset($value['count']))
				{
					unset($value['count']);
				}
				if(count($value) == 1)
				{
					$value = $value[0];
				}
			}
		}
		//Zend_Debug::dump($userInfo, 'collapsed $userInfo');
		return $userInfo;
	}
	
	
	/**
	 * 
	 * @param $uid
	 * @return array
	 */
	protected static function _setLDAPUserInfo($uid)
	{
		$appConfig = Zend_Controller_Front::getInstance()->getParam('appconfig');
		//Zend_Debug::dump("in ldap func");
		if($appConfig['requirelogin'])
		{
			$userInfo = self::getLDAPUserInfo($uid);
			//Zend_Debug::dump($userInfo, 'collapsed $userInfo');exit;
			$userInfo['bushido_user_id'] = $userInfo['employeenumber'];
			unset($userInfo['employeenumber']);
			
			$userInfo['roles'] = $userInfo['nsrole'];
			unset($userInfo['nsrole']);	
			
			foreach($userInfo['roles'] as $index => &$role)
			{
				$adapter = Bushido_Db_Table::getAdapter();
				$roleName = end(split('cn=', current(split(',', $role))));
				$role = $adapter->fetchOne('SELECT ldap_group_id FROM ldap_group WHERE name = ?', $roleName);
				if(empty($role))
				{
					unset($userInfo['roles'][$index]);
				}
				
				$team = $adapter->fetchOne('SELECT team_id FROM ldap_group WHERE name = ?', $roleName);
				if($team)
				{
					$userInfo['teams'][] = $team;
				}
			}
			//Zend_Debug::dump($userInfo, 'collapsed and modded $userInfo');exit;
		}
		else
		{
			//Zend_Debug::dump("ldap func no login req");
		}
		//Zend_Debug::dump($userInfo, '$userinfo from ldap');
		return $userInfo;
	}
	
	/**
 	 * 
 	 * @param array $userInfo
 	 * @return unknown_type
 	 */
	public static function setUserRoles($userInfo)
	{
		//echo __FILE__ . ' ' . __LINE__ . "<br /> \n";
		$userTable = Bushido_Db_Table::getTable('Bushido_DbTable_User');
		$user = $userTable->find($userInfo['bushido_user_id'])->current();
		$userRoles = $user->findBushido_DbTable_UserRole();
		//echo __FILE__ . ' ' . __LINE__ . "<br /> \n";
		//echo $userRoles->count();exit;

		foreach($userRoles as $userRole)
		{
			if($userRole->findParentBushido_DbTable_Role()->ldap_group_id)
			{
				$userRole->delete();
			}
			
		}
		if(!is_array($userInfo['roles']))
		{
			$userInfo['roles'] = array($userInfo['roles']);
		}
		
		foreach($userInfo['roles'] as $groupId)
		{
			if($groupId)
			{
				$newUserEDRoles = Bushido_Db_Table::getTable('Bushido_DbTable_Role')->search(array('ldap_group_id' => $groupId));
				//Zend_Debug::dump($newUserEDRoles->count());exit;
				foreach($newUserEDRoles as $newUserEDRole)
				{
					Bushido_Db_Table::getTable('Bushido_DbTable_UserRole')->insert
					(
						array
						(
							'bushido_user_id' => $userInfo['bushido_user_id'],
							'bushido_role_id' => $newUserEDRole->bushido_role_id,
						)
					);
					
					if($newUserEDRole->bushido_role_id == Bushido_DbTable_Role::ADMIN)
					{
						Bushido_App::session()->userInfo['admin_bushido_user_id'] = $userInfo['bushido_user_id'];
					}
				}
			}
		}
	}
	
	/**
 	 * 
 	 * @param array $userInfo
 	 * @return unknown_type
 	 */
	public static function setUserTeams($userInfo)
	{
		//echo __FILE__ . ' ' . __LINE__ . "<br /> \n";
		$userTable = Bushido_Db_Table::getTable('Bushido_DbTable_User');
		$user = $userTable->find($userInfo['bushido_user_id'])->current();
		$userTeams = $user->findBushido_DbTable_UserTeam();
		//echo __FILE__ . ' ' . __LINE__ . "<br /> \n";
		//echo $userTeams->count();exit;

		foreach($userTeams as $userTeam)
		{
			{
				$userTeam->delete();
			}
		}
		
		if(!is_array($userInfo['teams']))
		{
			$userInfo['teams'] = array($userInfo['teams']);
		}
		
		foreach(array_unique($userInfo['teams']) as $teamId)
		{
			if($teamId)
			{
				$newUserTeams = Bushido_Db_Table::getTable('Bushido_DbTable_Team')->search(array('team_id' => $teamId));
				//Zend_Debug::dump($newUserTeams->count());exit;
				foreach($newUserTeams as $newUserTeam)
				{
					Bushido_Db_Table::getTable('Bushido_DbTable_UserTeam')->insert
					(
						array
						(
							'bushido_user_id' => $userInfo['bushido_user_id'],
							'team_id' => $newUserTeam->team_id,
						)
					);
				}
			}
		}
	}
	
	
	/**
	 * 
	 * @return void
	 */
	public static function main()
	{
		$app = new Bushido_App();
		$app->init();
		$app->getFrontController()->dispatch();
	}
	
	
	/**
	 * 
	 * @param $recipient
	 * @param $subject
	 * @param $description
	 * @param $details
	 * @return void
	 */
	public static function email($recipients, $subject, $description, $details)
	{
		$mail = new Zend_Mail();
		
		$allowedRecipients = array
		(
			'Elva.White@chi.frb.org'
		);
		
		$mail->setFrom('tg_is_portal@chi.frb.org', 'IS Portal');
		if(!is_array($recipients))
		{
			$recipients = array($recipients);
		}
		
		foreach($recipients as $recipient)
		{
			if(in_array($recipient, $allowedRecipients))
			{
				$mail->addTo($recipient);
			}
		}
		unset($recipient);
		//$mail->setSubject($subject);
		
		
		
		$mail->addTo('nathan.keyes@chi.frb.org');
		//$mail->addTo('jacob.middleton@chi.frb.org');
		$mail->setSubject('IS Portal test email(Ignore this if you are not expecting it): '. $subject);
		$details = $details . print_r($recipients, true);
		
		
		$view = Zend_Layout::getMvcInstance()->getView();
		$html = $view->partial('email/body.phtml', 'default', array('description' => $description, 'details' => $details));
		$mail->setBodyHtml($html);
		$mail->send();
	}
	/*
	public static function __get($key)
	{
		return Bushido_App::session()->$key;
	}
	
	public  static function __set($key, $value)
	{
		return Bushido_App::session()->$key = $value;
	}
	*/
	/**
	 * 
	 * @return Zend_Session_Namespace
	 */
	public static function session()
	{
		$appConfig = Zend_Controller_Front::getInstance()->getParam('appconfig');

		//init session object
		$session = new Zend_Session_Namespace($appConfig['appname']);
		return $session;
	}
	/**
	 * 
	 * @return Bushido_Db_Table_Row
	 */
	public static function getUser()
	{
		//Zend_Debug::dump(Bushido_App::session()->userInfo, 'session bushido_user_id');
		$user = null;
		if(Bushido_App::session()->userInfo['bushido_user_id'])
		{
			$adapter = Bushido_Db_Table::getAdapter();
			$userData = $adapter->fetchRow("SELECT * FROM bushido_user WHERE bushido_user_id = ?", Bushido_App::session()->userInfo['bushido_user_id'], Zend_Db::FETCH_ASSOC);
	
			$user = new Bushido_DbTable_User_Row
			(
				array
				(
					'table'    => Bushido_Db_Table::getTable('Bushido_DbTable_User'),
					'data'     => $userData,
					'stored'   => true,
					'readOnly' => false
				)
			);
		}
		//Zend_Debug::dump($user, 'user obj');exit;
		return $user;
		
	}
	
	/**
	 * 
	 * @param $database
	 * @return Zend_Db_Adapter_Abstract
	 */
	public static function getAdapter($database = null)
	{
		$adapter = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getPluginResource('dbmulticonnection')->getAdapter($database);
		return $adapter;
		
	}
}